package com.glory.cqaospda.view

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Intent
import android.content.IntentFilter
import android.content.IntentFilter.MalformedMimeTypeException
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.NfcA
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.Settings
import android.text.InputType
import android.view.KeyEvent
import android.view.View
import com.glory.cqaospda.R
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.bean.UserInfoEntry
import com.glory.cqaospda.utils.ByteArrayChange.ByteArrayToHexString
import com.glory.cqaospda.utils.EditTextEnterUtils
import com.glory.cqaospda.viewmodel.WorkCardModel
import com.glory.mvvmnet.base.BaseActivity
import com.glory.mvvmnet.entity.ToastMessageBean
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_title.*
import java.util.*


class WorkCardActivity : BaseActivity<WorkCardModel>() {

    var mNfcAdapter: NfcAdapter? = null
    var mPendingIntent: PendingIntent? = null
    lateinit var mFilters: Array<IntentFilter>
    lateinit var mTechLists: Array<Array<String>>
    lateinit var data3: ByteArray
    var type = "0"
    private var bIndex: Int = 0
    private var bCount: Int = 0
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when(msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@WorkCardActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }

    override fun initData() {
        lineWorkCard.visibility = View.VISIBLE

        ivPassword.setOnClickListener{
            val pos = etPassword.selectionStart
            if (etPassword.inputType !== InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD) {
                etPassword.inputType =
                    InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                ivPassword.setImageDrawable(getResources().getDrawable(R.drawable.mi))
            } else {
                etPassword.inputType =
                    InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

                ivPassword.setImageDrawable(getResources().getDrawable(R.drawable.ming))
            }
            etPassword.setSelection(pos)
        }

        btnLogin.setOnClickListener {
            if (Constant.isFastClick()) {
                if (type != "0") {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请先验证工号", false)
                    return@setOnClickListener
                }
                if (etWorkCard.text.toString().trim { it <= ' ' }.isEmpty()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请输入工号", false)
                    return@setOnClickListener
                }
                if (etUser.text.toString().trim { it <= ' ' }.isEmpty()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请输入账号", false)
                    return@setOnClickListener
                }
                if (etPassword.text.toString().trim { it <= ' ' }.isEmpty()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请输入密码", false)
                    return@setOnClickListener
                }

                if (etPassword.text.toString() != etAgainPassword.text.toString()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("两次密码不一致，请重新输入", false)
                    return@setOnClickListener
                }
                viewModel.getLoginData(
                    etWorkCard.text.toString(),
                    etUser.text.toString(),
                    etPassword.text.toString()
                )
            }
        }

        queryNFCData(etWorkCard)

        viewModel.defUI.callObserve.observe(this) {
           if (!Constant.okgoError) {
               when (it.type) {
                   1 -> {
                       val userInfoEntry = it.item as UserInfoEntry
                       type = userInfoEntry.type
                       if (userInfoEntry.type == "0") {
                           btnLogin.text = userInfoEntry.usertype
                       } else {
                           viewModel.defUI.toastEvent.value = ToastMessageBean("录入成功", true)
                           finish()
                       }
                   }
               }
           }else{
               Constant.okgoError = false
           }
        }

    }

    override fun initView(savedInstanceState: Bundle?) {
        btnLogin.text = "提交"
        llAgainPassword.visibility = View.VISIBLE
        checkNFCFunction() // NFC Check

        val instance = MyApp.instance
        instance!!.handler = handler
        mPendingIntent = PendingIntent.getActivity(
            this, 0, Intent(
                this,
                javaClass
            ).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)
        // Setup an intent filter for all MIME based dispatches
        val ndef = IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)
        try {
            ndef.addDataType("*/*")
        } catch (e: MalformedMimeTypeException) {
            throw RuntimeException("fail", e)
        }
        mFilters = arrayOf(ndef)

        // 根据标签类型设置
        mTechLists = arrayOf(arrayOf(NfcA::class.java.name))

    }

    override fun layoutId(): Int {
        return R.layout.activity_login
    }

    private fun checkNFCFunction() {
        // TODO Auto-generated method stub
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this)
        // check the NFC adapter first
        if (mNfcAdapter == null) {

            FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "该设备未发现NFC功能", {

            }) {}.show(supportFragmentManager, "SUBMIT_DIALOG")

            return
        } else {
            if (!mNfcAdapter!!.isEnabled) {
                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "NFC未开启,是否去开启？", {
                    val setnfc = Intent(Settings.ACTION_NFC_SETTINGS)
                    startActivity(setnfc)
                }) {}.show(supportFragmentManager, "SUBMIT_DIALOG")
                return
            }
        }
    }

    override fun onResume() {
        super.onResume()
        enableForegroundDispatch()
    }

    private fun enableForegroundDispatch() {
        // TODO 自动生成的方法存根
        if (mNfcAdapter != null) {
            mNfcAdapter!!.enableForegroundDispatch(
                this, mPendingIntent,
                mFilters, mTechLists
            )
        }
    }

    override fun onNewIntent(intent: Intent) {
        // TODO 自动生成的方法存根
        super.onNewIntent(intent)
        val intentActionStr = intent.action // 获取到本次启动的action
        if (NfcAdapter.ACTION_NDEF_DISCOVERED == intentActionStr || NfcAdapter.ACTION_TECH_DISCOVERED == intentActionStr || NfcAdapter.ACTION_TAG_DISCOVERED == intentActionStr) { // 未知类型
            // 在intent中读取Tag id
            val tag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
            val bytesId = tag!!.id // 获取id数组
            etWorkCard.setText(ByteArrayToHexString(bytesId))
            viewModel.getLoginData(ByteArrayToHexString(bytesId), "", "")
        }
    }

    private fun queryNFCData(
        editText: FreeUI_ClearEditText?,
    ) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            viewModel.getLoginData(s!!, "", "")
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1) {
            FreeApi_LogUtils.saveErrorMessages(resultCode.toString(), "resultCode")

            when (resultCode) {
                108 -> {
                    finish()
                }
            }
        }
    }
    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            FreeApi_LogUtils.saveErrorMessages("KeyEvent", "KeyEvent")

            intent.putExtra("type", "KeyEvent")
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivityForResult(intent, 1)
            return false
        }
        return super.onKeyUp(keyCode, event)
    }

}